<template>
  <p-card :bordered="false" style="height: 100%">

    <div class="table-page-search-wrapper">
      <p-form layout="inline">
        <p-row :gutter="24" v-if="queryInfo && queryInfo.length>0">
          <template v-for="(item,index) in queryInfo">
            <template v-if=" item.hidden==='1' ">
              <p-col v-if="item.view.indexOf('Date')>=0" :md="6" :sm="8" :key=" 'query'+index " v-show="toggleSearchStatus">
                <onl-cgreport-query-form-item :queryParam="queryParam" :item="item" :dictOptions="dictOptions"></onl-cgreport-query-form-item>
              </p-col>
              <p-col v-else :md="6" :sm="8" :key="'query'+index " v-show="toggleSearchStatus">
                <onl-cgreport-query-form-item :queryParam="queryParam" :item="item" :dictOptions="dictOptions"></onl-cgreport-query-form-item>
              </p-col>
            </template>
            <template v-else>
              <p-col v-if="item.view.indexOf('Date')>=0" :md="6" :sm="8" :key=" 'query'+index ">
                <onl-cgreport-query-form-item :queryParam="queryParam" :item="item" :dictOptions="dictOptions"></onl-cgreport-query-form-item>
              </p-col>
              <p-col v-else :md="6" :sm="8" :key="'query'+index ">
                <onl-cgreport-query-form-item :queryParam="queryParam" :item="item" :dictOptions="dictOptions"></onl-cgreport-query-form-item>
              </p-col>
            </template>
          </template>
          <p-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <p-button type="primary" @click="searchByQuery" icon="search">查询</p-button>
              <p-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</p-button>
      <p-button type="primary" icon="plus" style="margin-left: 8px" @click="exportExcel">导出</p-button>

              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <p-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>

    <div class="table-operator" style="margin-bottom: 10px">
      <template v-if="cgButtonList && cgButtonList.length>0" v-for="(item,index) in cgButtonList">
          <p-button
            v-if=" item.optType=='js' "
            :key=" 'cgbtn'+index "
            @click="cgButtonJsHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon">
            {{ item.buttonName }}
          </p-button>
          <p-button
            v-else-if=" item.optType=='action' "
            :key=" 'cgbtn'+index "
            @click="cgButtonActionHandler(item.buttonCode)"
            type="primary"
            :icon="item.buttonIcon">
            {{ item.buttonName }}
          </p-button>
        </template>
    </div>

    <p-table
      ref="table"
      size="middle"
      bordered
      rowKey="id"
      :columns="table.columns"
      :dataSource="table.dataSource"
      :pagination="table.pagination"
      :loading="table.loading"
      :scroll="table.scroll"
      :rowSelection=" { type: rowSelectionType, fixed: true, selectedRowKeys: table.selectedRowKeys, onChange: handleChangeInTableSelect }"
      @change="handleChangeInTable"
      style="min-height: 300px"
      width="100%"
    >

      <!-- 支持链接href跳转 -->
      <template
        v-for="field of fieldHrefSlots"
        :slot="field.slotName"
        slot-scope="text, record"
      >
        <a @click="handleClickFieldHref(field,record)">{{ text }}</a>
      </template>

    </p-table>

    <!-- 跳转Href的动态组件方式 -->
    <p-modal v-bind="hrefComponent.model" v-on="hrefComponent.on">
      <component :is="hrefComponent.is" v-bind="hrefComponent.params"/>

    </p-modal>

  </p-card>
</template>

<script>
  import { HrefJump } from '@/mixins/OnlAutoListMixin'
  import { getAction, downFile } from '@/api/manage'
  import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
  import { filterObj } from '@/utils/util'
  import onlCgreportQueryFormItem from '@/components/jeecgbiz/modules/OnlCgreportQueryFormItem'
  export default {
    name: 'OnlCgreportAutoList',
    mixins: [HrefJump],
    components: { onlCgreportQueryFormItem },
    props: {
      recode: {
        type: String,
        default: ''
      },
      context: {
        type: String,
        default: ''
      },
      isMultiSelect: {
        type: String,
        default: ''
      },
      isChildren: {
        type: Boolean,
        default: false
      },
    },
    data () {
      return {
        EnhanceJS:'',
        cgButtonLinkList: [],
        cgButtonList: [],
        // 查询参数
        queryInfo: [],
        // 查询参数，多个页面的查询参数用 code 作为键来区分
        queryParamsMap: {},
        selfParam: {
        },
        sorter: {
          column: '',
          order: 'desc',
        },
        dictOptions: {},
        toggleSearchStatus: false, // 高级搜索 展开/关闭
        reportCode: this.recode,
        description: '在线报表功能测试页面',
        url: {
          getColumnsAndData: this.context + '/online/cgreport/api/getColumnsAndData/',
          getQueryInfo: this.context + '/online/cgreport/api/getQueryInfo/',
          getParamsInfo: this.context + '/online/cgreport/api/getParamsInfo/',
          getButtonData:this.context +  '/online/cgreport/api/getButtonData',
        },
        table: {
          loading: true,
          // 表头
          columns: [],
          // 数据集
          dataSource: [],
          // 选择器
          selectedRowKeys: [],
          selectionRows: [],
          scroll: { x: false },
          // 分页参数
          pagination: {
            current: 1,
            pageSize: 10,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
          }
        },
        cgreportHeadName: ''
      }
    },

    mounted () {
      this.context === '' ? console.log('没有传入微服务字段') : console.log('弹窗使用的微服务是：' + this.context)
      this.initParamsInfo()
      this.initQueryInfo()
      this.initButtonList()
    },
    watch: {
      '$route' () {
        // 刷新参数放到这里去触发，就可以刷新相同界面了
        this.initParamsInfo()
        this.initQueryInfo()
      },
      recode: {
        deep: true,
        handler (val) {
          this.reportCode = val
        }
      }
    },
    computed: {
      queryParam: {
        get () {
          return this.queryParamsMap[this.reportCode]
        },
        set (newVal) {
          this.$set(this.queryParamsMap, this.reportCode, newVal)
        }
      },
      rowSelectionType () {
        if (this.isMultiSelect == 'popup_multi') {
          return 'checkbox'
        } else {
          return 'radio'
        }
      }
    },
    methods: {
      initButtonList () {
        getAction(`${this.url.getButtonData}/${this.reportCode}/search`).then((res) => {
          console.log('--获取自定义按钮->>', res)
          if (res.success) {
            this.code = res.data.result.code
            this.initCgButtonList(res.data.result.cgButtonList)
            this.initCgEnhanceJs(res.data.result.enhanceJs)
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      initCgEnhanceJs (enhanceJs) {
        // console.log("--onlineList-js增强",enhanceJs)
        if (enhanceJs) {
          const Obj = eval('(' + enhanceJs + ')')
          this.EnhanceJS = new Obj(getAction, postAction, deleteAction)
          this.cgButtonJsHandler('created')
        } else {
          this.EnhanceJS = ''
        }
      },
      initCgButtonList (btnList) {
        const linkArr = []
        const buttonArr = []
        if (btnList && btnList.length > 0) {
          for (let i = 0; i < btnList.length; i++) {
            const temp = btnList[i]
            if (temp.buttonStyle == 'button') {
              buttonArr.push(temp)
            } else if (temp.buttonStyle == 'link') {
              linkArr.push(temp)
            }
          }
        }
        this.cgButtonLinkList = [...linkArr]
        this.cgButtonList = [...buttonArr]
        console.log('链接增强', this.cgButtonLinkList)
      },
      cgButtonJsHandler (buttonCode) {
        if (this.EnhanceJS[buttonCode]) {
          this.EnhanceJS[buttonCode](this)
        }
      },
      setTableRow () {
        this.table.selectedRowKeys = [],
          this.table.selectionRows = []
      },
      initParamsInfo () {
        if (!this.reportCode) {
          return false
        }
        // 获取报表ID
        if (!this.queryParam) {
          this.queryParam = {}
        }

        this.selfParam = {}
        getAction(`${this.url.getParamsInfo}${this.reportCode}`).then((res) => {
          if (res.success) {
            if (res.data && res.data.length > 0) {
              for (const i of res.data) {
                this.selfParam['self_' + i.paramName] = (!this.$route.query[i.paramName]) ? '' : this.$route.query[i.paramName]
              }
            }
          } else {
            this.$message.warning(res.msg)
          }
          this.loadData()
        })
      },
      initQueryInfo () {
        if (!this.reportCode) {
          return false
        }
        getAction(`${this.url.getQueryInfo}${this.reportCode}`).then((res) => {
          if (res.success) {
            this.queryInfo = res.data
          } else {
            this.$message.warning(res.msg)
          }
        })
      },
      loadData (arg) {
        if (!this.reportCode) {
          return false
        }
        if (arg == 1) {
          this.table.pagination.current = 1
        }
        const params = this.getQueryParams()// 查询条件
        // 获取报表ID
        this.table.loading = true

        getAction(`${this.url.getColumnsAndData}${this.reportCode}`, params).then(res => {
          if (res.success) {
            const { data, columns, cgreportHeadName, dictOptions, fieldHrefSlots } = res.data

            const columnWidth = 230
            this.dictOptions = dictOptions
            for (let a = 0; a < columns.length; a++) {
              if (columns[a].customRender) {
                const field_name = columns[a].customRender
                columns[a].customRender = t => t ? filterMultiDictText(this.dictOptions[field_name], t + '') : t
              }
              columns.width = columnWidth
            }
            this.table.scroll.x = columns.length * columnWidth
            this.table.columns = [...columns]
            this.cgreportHeadName = cgreportHeadName
            this.fieldHrefSlots = fieldHrefSlots
            if (data) {
              this.table.pagination.total = Number(data.total)
              this.table.dataSource = data.records
            } else {
              this.table.pagination.total = 0
              this.table.dataSource = []
            }
          } else {
            this.$message.warn('查询失败：' + res.msg)
          }
        }).catch((e) => {
          console.error(e)
          this.$message.error('查询失败')
        }).finally(() => {
          this.table.loading = false
        })
      },
      getQueryParams () {
        const param = Object.assign({}, this.queryParam, this.sorter, this.selfParam)
        if(this.isChildren){
          const t = sessionStorage.getItem('customValue')
          const p = JSON.parse(t)
          if(p.supno){
            param.supno = p.supno
          } 
        }
        param.pageNo = this.table.pagination.current
        param.pageSize = this.table.pagination.pageSize
        return filterObj(param)
      },
      searchByQuery () {
        this.loadData(1)
      },
      searchReset () {
        this.queryParam = {}
        this.loadData(1)
      },
      handleToggleSearch () {
        this.toggleSearchStatus = !this.toggleSearchStatus
      },
      exportExcel () {
        const fileName = this.cgreportHeadName
        const selfParam = {}
        for (const queryName in this.$route.query) {
          if (this.$route.query.hasOwnProperty(queryName)) {
            const value = this.$route.query[queryName]
            selfParam['self_' + queryName] = value || ''
          }
        }
        downFile(`/online/cgreport/api/exportXls/${this.reportCode}`, Object.assign(selfParam, this.queryParam)).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
          } else {
            const url = window.URL.createObjectURL(new Blob([data]))
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + '.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) // 下载完成移除元素
            window.URL.revokeObjectURL(url) // 释放掉blob对象
          }
        })
      },
      handleChangeInTableSelect (selectedRowKeys, selectionRows) {
        // console.log('selectedRowKeys:', selectedRowKeys)
        // console.log('selectionRows:', selectionRows)
        // if(this.table.selectedRowKeys.length == 1 ){
        //   this.table.selectedRowKeys = selectedRowKeys
        //   this.table.selectedRowKeys.splice(0,1)
        // }else{
        //   this.table.selectedRowKeys = selectedRowKeys
        // // }
        this.table.selectionRows = []
        this.table.selectionRows = selectionRows
        this.table.selectedRowKeys = selectedRowKeys
        // 多选
        if (this.isMultiSelect == 'popup_multi') {
          this.$emit('callback', selectionRows)
        } else {
          this.$emit('callback', selectionRows[0])
        }
      },
      onSelect (record, selected) {
        // console.log("record", record)
        // console.log("selected", selected)
        if (selected == true) {
          this.table.selectionRows.push(record)
        } else {
          this.table.selectionRows.forEach(function (item, index, arr) {
            if (item.id == record.id) {
              arr.splice(index, 1)
            }
          })
        }
      },
      handleChangeInTable (pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        if (Object.keys(sorter).length > 0) {
          this.sorter.column = sorter.field
          this.sorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        } else {
          this.sorter.column = null
          this.sorter.order = null
        }
        this.table.pagination = pagination
        this.loadData()
      }

    }
  }
</script>
<style scoped>
  .div {
    display: flex;
    align-items: center;
    height: 500px
  }

</style>
